package com.ktjiaoyu.server.controller;

import com.ktjiaoyu.server.pojo.Admin;
import com.ktjiaoyu.server.pojo.AdminLoginParam;
import com.ktjiaoyu.server.pojo.RespBean;
import com.ktjiaoyu.server.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api("登录接口")
public class LoginController {
    @Resource
    IAdminService adminService;

    @PostMapping("/login")
    @ApiOperation("登录")
    @ApiParam(name="adminLoginParam",value = "登录信息的包装类",required = true)
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        return adminService.login(adminLoginParam,request);
    }

    @PostMapping("/logout")
    @ApiOperation("退出")
    public RespBean logout() {
        return RespBean.success("注销成功！");
    }

    @GetMapping("/admin/info")
    @ApiOperation("获取用户信息")
    public RespBean getAdminInfo(Principal principal) {
        if(null == principal) {
            return null;
        }
        // principal得到的是AdminServiceImpl类里login方法中UsernamePasswordAuthenticationToken对象中参数一的值，即当前登录的用户对象。
        String username = principal.getName(); // username得到的是当前登录用户的用户名
        // 根据用户名获取完整的用户对象
        Admin admin = adminService.getAdminByUserName(username);
        admin.setPassword(null);  //出于对密码的安全考虑，密码返回null
        admin.setRoles(adminService.findRolesByAdminId(admin.getId()));

        Map<String, Object> map = new HashMap<String,Object>();
        map.put("admin",admin);
        map.put("permissions", adminService.findMenuUrlByAdminId(admin.getId()));

        return RespBean.success("获取用户信息",map);
    }
}
